import React from 'react';
import { Redirect, Route, Switch } from 'react-router-dom';

import { Layout } from 'antd';

import memory from '../../utils/memoryUtils';
import LeftNav from '../../components/LeftNav';
import Header from '../../components/Header';

import Home from '../Home';
import Category from '../Category';
import Product from '../Product';
import User from '../User';
import Role from '../Role';
import BarCharts from '../Charts/BarCharts';
import LineCharts from '../Charts/LineCharts';
import PieCharts from '../Charts/PieCharts';

const { Footer, Sider, Content } = Layout;

function hasAuth(path) {
    const menus = memory.user.role.menus;
    const {username} = memory.user;
    if (username === 'admin') return true;
    return menus.includes(path) || menus.some(item => path.includes(item));
}

export default function Admin() {

    React.useEffect(() => {
        document.title = 'GULI-Mall管理';
    }, []);

    // 如果内存中没有用户信息，表示当前没有登录，跳转到登录页面
    const { user } = memory;
    if (!user || !user._id) {
        return <Redirect to="/login" />
    }

    return (
        <Layout style={{ 'height': '100%' }}>
            <Sider>
                <LeftNav />
            </Sider>
            <Layout>
                <Header>Header</Header>
                <Content style={{ padding: '20px 20px 0' }}>
                    <Switch>
                        <Route path="/home" component={Home} />
                        {hasAuth('/category') ? <Route path="/category" component={Category} /> : null}
                        {hasAuth('/product') ? <Route path="/product" component={Product} /> : null}
                        {hasAuth('/user') ? <Route path="/user" component={User} /> : null}
                        {hasAuth('/role') ? <Route path="/role" component={Role} /> : null}
                        {hasAuth('/charts/line') ? <Route path="/charts/line" component={LineCharts} /> : null}
                        {hasAuth('/charts/bar') ? <Route path="/charts/bar" component={BarCharts} /> : null}
                        {hasAuth('/charts/pie') ? <Route path="/charts/pie" component={PieCharts} /> : null}
                        <Redirect to="/home" />
                    </Switch>
                </Content>
                <Footer style={{ 'textAlign': 'center', 'color': '#aaa', 'padding': '10px' }}>推荐使用谷歌浏览器，以获取更佳页面操作体验</Footer>
            </Layout>
        </Layout>
    )
}
